package com.lottery.web.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.lottery.common.util.Constant;
import com.lottery.web.model.Account;
import com.lottery.web.service.UserMgrService;

/**
 * 登陆模块
 * @author linzhimou
 * @since 2016年10月20日
 */
@Controller
public class LoginController extends BaseController{

	private static Logger logger = Logger.getLogger(LoginController.class);
	
	@Resource
	private UserMgrService userService;

	/** 用户登陆验证*/
	@RequestMapping("/login")
	@ResponseBody
	public String login(Account account, HttpSession session){
		//校验account
		
		try{
			Account user = userService.getUser(account);
			
			if(user != null){
				//将用户信息保存到session中
				session.setAttribute(Constant.USER, user);
				session.setAttribute(Constant.USERCODE, user.getUserCode());
			} else {
				return errorResult("用户不存在或密码错误");
			}
			
		} catch (Exception ex){
			logger.error("login error", ex);
			return errorResult("登陆异常");
		}
		
		return jsonResult(null);
	}
	
	@RequestMapping("/index")
	public ModelAndView index(HttpSession session, Model model){
		//校验account
		
		String page = "error";
		try{
			Account user = (Account) session.getAttribute(Constant.USER);
			page = userIndexPage(user);
			
			model.addAttribute("user", user);
		} catch (Exception ex){
			logger.error("login error", ex);
			model.addAttribute(Constant.ERRORMSG, "登陆异常");
		}
		
		return new ModelAndView(page);
	}
	
	
	/** 根据角色不同返回不同的页面 */
	private String userIndexPage(Account user){
		String page = "/player/index";
		if(user.getRole().equals(Constant.ADMIN)){
			//管理员首页
			page = "/admin/index";
		} else if (user.getRole().equals(Constant.AGENT)){
			//代理首页
			page = "/agent/index";
		}
		
		return page;
	}
	
	/**登出*/
	@RequestMapping("/logout")
	public void logout(HttpSession httpSession,
			HttpServletRequest request, 
			HttpServletResponse response) throws IOException{
		httpSession.removeAttribute(Constant.USER);
		httpSession.invalidate();
		String contextPath = request.getContextPath();
		response.sendRedirect(contextPath + "/static/layout/login.jsp");
	}
	
}
